<script setup lang="ts">
import Table from '@/components/table/index.vue';
import useGetList from '@/hooks/useGetList';
import { getShipDataRecord, uploadShipData, GetShipDataRecordParams, ShipDataRecord } from '@/services/data';
import { ElButton, ElMessage, ElMessageBox, UploadFile, UploadFiles } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { deleteRegionFromId, ExerciseRegion, getRegionsFromTimeRange } from 'common/src/apis';
import { getCustomLocalTimeFormat } from 'common/src/utils/time';
import { regionOptions } from 'common/src/utils/special';

interface Props {
  visible: boolean;
  active: boolean;
}

interface Emits {
  (e: "update:visible", visible: boolean): void;
}

let listAll: ExerciseRegion[] = [];

const getListFC = async (params: GetShipDataRecordParams) => {
  try {
    if (!listAll.length) {
      const res = await getRegionsFromTimeRange({start: 0, end: new Date('2099-01-01').valueOf()});
      listAll = res.data as ExerciseRegion[] || [];
    }
    const { page, length } = params;
    return {
      list: listAll.slice((page - 1) * length, page * length).map((record, idx) => ({
        ...record,
        index: idx + 1 + (page - 1) * length,
      })),
      total: listAll.length || 0,
      page: params.page || 1,
      size: params.length || 15,
    };
  } catch {
    return {
      list: [],
      total: 0,
      page: 1,
      size: 15,
    };
  }
};

const props = defineProps<Props>();
const emits = defineEmits<Emits>();
const {
  list,
  getList,
  loading,
  total,
  page,
  size,
} = useGetList(getListFC);
const dbFiles = ref<UploadFiles>([]);
const uploadLoading = ref(false);

const handleDeleteRow = async (row: any) => {
  await ElMessageBox.confirm(`确定删除序号为“${row.index}”的碍航区吗？`, '删除碍航区', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  });
  try {
    await deleteRegionFromId(row.id);
    ElMessage({
      type: 'success',
      message: '操作成功',
    });
    handleQuery(1, page.value);
  } catch {
    ElMessage({
      type: 'warning',
      message: '操作失败，请重试',
    });
  }
};

const show = computed({
  get() {
    return props.visible;
  },
  set(visible: boolean) {
    emits("update:visible", visible);
  },
});

const columns = [
  {
    prop: 'index',
    label: '序号',
    align: 'center',
    width: 80,
  },
  {
    prop: 'name',
    label: '名称',
    align: 'center',
    render: (columnsProps: { row: ExerciseRegion }) => {
      const { name } = columnsProps.row;
      return h('div', {innerHTML: name?.replaceAll('color:black', 'color:#fff')});
    },
  },
  {
    prop: 'description',
    label: '描述',
    align: 'center',
  },
  {
    label: '区域类型',
    align: 'center',
    width: 120,
    render: (columnsProps: { row: ExerciseRegion }) => {
      const { type } = columnsProps.row;
      const label = regionOptions.find(opt => opt.value === type)?.label || '--';
      return h('div', null, label);
    },
  },
  {
    prop: 'created_time',
    label: '入库时间',
    align: 'center',
    width: 140,
  },
  {
    prop: 'depart',
    label: '持续时间',
    align: 'center',
    width: 200,
    render: (columnsProps: { row: ExerciseRegion }) => {
      const { beginDate, dueDate } = columnsProps.row;
      const stime = beginDate ? getCustomLocalTimeFormat(beginDate, 'YYYY-MM-DD HH:mm') : '--';
      const etime = dueDate ? getCustomLocalTimeFormat(dueDate, 'YYYY-MM-DD HH:mm') : '--';
      return h('div', null, [
        h('div', null, stime),
        h('div', null, etime),
      ]);
    },
  },
  {
    label: '操作',
    align: 'center',
    width: 120,
    // fixed: 'right',
    renderBtns: [
      {
        text: '删除',
        onClick: (_idx: number, row: any) => handleDeleteRow(row),
        type: 'danger',
        link: true,
        disableFn: (_idx: number, row: ExerciseRegion) => !row.isDeletable,
      },
    ]
  },
];

const handleQuery = (page: number, length: number) => {
  getList({ page, length });
};

const handleDbFileUpload = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  dbFiles.value = uploadFiles;
};

const handleUploadShipData = async () => {
  uploadLoading.value = true;
  try {
    const formData = new FormData();
    dbFiles.value.forEach(file => {
      formData.append('dbname', file.raw as any as File);
    })
    await uploadShipData(formData);
    ElMessage({
      type: 'success',
      message: '数据导入成功',
    });
    show.value = false;
    handleQuery(1, size.value);
  } catch {
    ElMessage({
      type: 'warning',
      message: '数据导入失败，请重试',
    });
  } finally {
    uploadLoading.value = false;
  }
};

const handleCancelUpload = () => {
  show.value = false;
  dbFiles.value = [];
};

onMounted(() => {
  handleQuery(1, size.value);
});
</script>

<template>
  <Table
    v-if="props.active"
    :loading="loading"
    :list="list"
    border
    height="calc(100vh - 35px - 62px - 50px - 40px - 60px)"
    :columns="columns"
    :total="total"
    :page-no="page"
    :page-size="size"
    :get-list="(pageNo: number, pageSize: number) => handleQuery(pageNo, pageSize)"
  />
  <ElDialog
    class="custom-dialog ship-db-upload-dialog"
    v-model="show"
    title="危险报文数据导入"
    width="400"
    align-center
    @close="() => handleCancelUpload()"
    append-to-body
  >
    <ElUpload
      class="ship-db-upload"
      drag
      multiple
      show-file-list
      :auto-upload="false"
      :file-list="dbFiles"
      @change="handleDbFileUpload"
    >
      <ElIcon class="el-icon--upload"><UploadFilled /></ElIcon>
      <div class="el-upload__text">
        拖入危险报文或者<em>点选危险报文上传</em>
      </div>
    </ElUpload>
    <div class="dialog-footer" style="padding-left: 0;">
      <ElButton class="custom-btn" @click="() => handleCancelUpload()">取消</ElButton>
      <ElButton type="primary" :loading="uploadLoading" @click="() => handleUploadShipData()">确定</ElButton>
    </div>
  </ElDialog>
</template>

<style lang="less" scoped>
</style>
